import * as Cesium from 'cesium'
/**
 * 求多边形面积质心（椭球面）
 * @param {number[][]} lonlats  [[lon,lat], …]  必须闭合（首末点可相同）
 * @returns {Cesium.Cartesian3}
 */
export function getCentroid(lonlats: { lon: number; lat: number }[]) {
  // 1. 转成 Cartographic 数组
  const positions = lonlats.map((p) => Cesium.Cartographic.fromDegrees(p.lon, p.lat))

  // 2. 用 Cesium 内置的 PolygonGeometry 计算质心
  const geom = new Cesium.PolygonGeometry({
    polygonHierarchy: new Cesium.PolygonHierarchy(positions.map((c) => Cesium.Cartographic.toCartesian(c))),
    vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
  })

  const center = Cesium.PolygonGeometry.createGeometry(geom)?.boundingSphere?.center
  return center // Cartesian3
}
export function listenMousePoint(viewer: Cesium.Viewer) {
  // 开启深度检测，保证拾取准确
  viewer.scene.globe.depthTestAgainstTerrain = true
  // 创建事件处理器
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction(function (movement: Cesium.ScreenSpaceEventHandler.PositionedEvent) {
    // 屏幕坐标 → 射线
    const ray = viewer.camera.getPickRay(movement.position)
    // 射线与地形求交
    const cartesian = viewer.scene.globe.pick(ray!, viewer.scene)

    if (cartesian) {
      // 笛卡尔 → 弧度 → 角度
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
      const lon = Cesium.Math.toDegrees(cartographic.longitude)
      const lat = Cesium.Math.toDegrees(cartographic.latitude)
      const alt = cartographic.height

      console.log(`经度: ${lon.toFixed(6)}°, 纬度: ${lat.toFixed(6)}°, 高程: ${alt.toFixed(2)} m`)

      // 可选：在点击处加一个红点到场景
      viewer.entities.add({
        position: cartesian,
        point: { pixelSize: 8, color: Cesium.Color.RED },
      })
    } else {
      console.log('未拾取到有效地形点，请确认点击位置或地形已加载。')
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
